package com.wechat.servlet.Friends;

import com.alibaba.fastjson.JSONArray;
import com.wechat.DAO.DaoImpl.UserInfoDAOIpml;
import com.wechat.DAO.DaoImpl.UserRelationDAOIpml;
import com.wechat.DAO.UserInfoDAO;
import com.wechat.DAO.UserRelationDAO;
import com.wechat.pojo.User;
import com.wechat.pojo.UserInfo;
import com.wechat.pojo.UserRelation;
import com.wechat.servlet.Utils.Base64Encoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AllFriendsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        UserInfoDAO userInfoDAO = new UserInfoDAOIpml();
        UserRelationDAO userRelationDAO = new UserRelationDAOIpml();
        List<UserInfo> userInfos = new ArrayList<>();
        try {
            List<UserRelation> relations = userRelationDAO.getAllRelation(username);
            if(relations!=null && !relations.isEmpty()){
                for (UserRelation userRelation: relations){
                    UserInfo userInfo = userInfoDAO.query(userRelation.getFID());
                    if(userInfo!=null){
                        userInfos.add(userInfo);
                    }
                }
            }else {
                response.getWriter().write("null");
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
            response.getWriter().write("fail");
            return;
        }
        if (userInfos!=null && !userInfos.isEmpty()){
            JSONArray jsonArray = (JSONArray) JSONArray.toJSON(userInfos);
            String json = jsonArray.toString();
            String base64 = Base64Encoder.encode(json);
            response.getWriter().write(base64);
            System.out.println("客户端获取到所有好友资料："+json);
        }
    }
}
